跳到主要内容

23 合并 K 个升序链表

https://leetcode.cn/leetbook/read/top-interview-questions-hard/xwcdnh/

cost: 12m37s

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/

struct CustomComparator {
bool operator()(ListNode* a, ListNode* b) { return a->val > b->val; }
};

class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, std::vector<ListNode*>, CustomComparator> q;
for (const auto head : lists) {
if (head != nullptr) {
q.push(head);
}
}
ListNode head = ListNode{};
head.next = nullptr;
ListNode* p = &head;
while (!q.empty()) {
p->next = q.top();
p = p->next;
q.pop();
if (p != nullptr && p->next != nullptr) {
q.push(p->next);
}
}
return head.next;
}
};